package com.mm.cme.kotlin_001.level02.i_006_demo_calculator

import com.mm.cme.kotlin_001.utils.pl

/**
 * Descriptions：计算器小程序
 * <p>
 * Author：ChenME
 * Date：2017/7/16
 * Email：ibelieve1210@163.com
 */
fun main(args: Array<String>) {
    while (true) {
        try {
            pl("请输入算式，例如：3 + 4")
            val input = readLine() ?: break
            val splits = input.trim().split(" ")
            if (splits.size < 3) {
                throw  IllegalArgumentException()
            }
            val arg1 = splits[0].toDouble()
            val op = splits[1]
            val arg2 = splits[2].toDouble()
            pl("$arg1 $op $arg2 = ${Operator(op)(arg1, arg2)}")

        } catch (e: NumberFormatException) {
            pl("您确定输入的是数字吗？")
        } catch (e: IllegalArgumentException) {
            pl("您确定输入的是三个参数吗？")
        } catch (e: Exception) {
            pl("亲爱的用户，程序遇到了未知的错误，${e.message}")
        }


        pl("再来一发？[y]")
        val cmd = readLine()
        if (null == cmd || cmd.toLowerCase() != "y") {
            break
        }
    }

    pl("感谢您的使用！！")
}

class Operator(op: String) {
    val opFun: (left: Double, right: Double) -> Double

    init {
        opFun = when (op) {
            "+" -> { l, r -> l + r }
            "-" -> { l, r -> l - r }
            "*" -> { l, r -> l * r }
            "/" -> { l, r -> l / r }
            "%" -> { l, r -> l % r }
            else -> {
                throw UnsupportedOperationException(op)
            }
        }
    }

    operator fun invoke(left: Double, right: Double): Double {
        return opFun(left, right)
    }
}